<?php

namespace App\Exceptions;

use Carbon\Carbon;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Exception\RouteNotFoundException;
use Throwable;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array<int, class-string<Throwable>>
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array<int, string>
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register()
    {
        $this->reportable(function (Throwable $e) {
            //
        });
    }

    public function render($request, Throwable $e) {
        $errCode = $e->getCode();
        $errMessage = $e->getMessage();

        //switch ($errCode) {
        //    //case $errCode >= 1000 && $errCode <= 1030:
        //    //case $errCode >= 2000 && $errCode <= 2030:
        //    //case $errCode >= 4000 && $errCode <= 4030:
        //    //    $statusCode = 200;
        //    //    break;
        //    case $errCode >= 3000 && $errCode <= 3030:
        //        $statusCode = 401;
        //        break;
        //    default:
        //        $statusCode = 200;
        //        break;
        //}

        $statusCode = 200;

        if ($e instanceof ValidationException) {
            $statusCode = 422;
            $errCode = 2000;
            $errMessage = array_values($e->errors())[0][0];
        }
        elseif($e instanceof RouteNotFoundException || $e instanceof NotFoundHttpException || $e instanceof MethodNotAllowedHttpException) {
            $statusCode = 404;
            $errCode = 1000;
            $errMessage = '无效请求';
        }
        elseif($e instanceof AuthenticationException) {
            $statusCode = 401;
            $errCode = 3000;
            $errMessage = '没有权限';
        }
        elseif($e instanceof ModelNotFoundException) {
            $statusCode = 200;
            $errCode = 4000;
            $errMessage = '数据不存在';
        }

        Log::error('['.$errMessage.']'.$e->getMessage());
        $log = [
            'file' => $e->getFile(),
            'line' => $e->getLine(),
            'code' => $e->getCode(),
            'message' => $e->getMessage()
        ];
        Log::error(json_encode($log));

        if (config('app.debug')) {
            $error = $e->getMessage().' [FILE]'.$e->getFile().' [LINE]'.$e->getLine().')';
        }

        return response()->json([
            'success' => false,
            'code' => $errCode,
            'error' => $error ?? null,
            'message' => $errMessage,
            'timestamp' => Carbon::now()->timestamp
        ])->setStatusCode($statusCode);
    }
}
